$(function () {
  init()

  let countdown = 60

  // 获取验证码
  $('#getCode').off('click').on('click', e => {
    if ($('#mobile').val().length === 11 &&
      /^[0-9]*$/.test($('#mobile').val()) &&
      $('#getCode').attr('disabled') === null) {
      sendCode($('#mobile').val())
    } else {
      utils.toast('手机号码格式错误')
    }
  })

  // 确认支付
  $('.buy').off('click').on('click', e => {
    analytics.send({
      event: `${av}-buy-click`,
      attr: {
        pid: productId || '',
        _c: channel || ''
      }
    })

    if ($('.login').css('display') === 'block') {
      const mobile = $('#mobile').val()
      const code = $('#code').val()
      if (mobile.length !== 11 ||
        !/^[0-9]*$/.test(mobile)) {
        utils.toast('手机号码格式错误')
        return
      }
      if (code.length !== 4 ||
        !/^[0-9]*$/.test(code)) {
        utils.toast('验证码格式错误')
        return
      }

      login(mobile, code, checkProductInfo)
    } else {
      checkProductInfo()
    }

    function checkProductInfo () {
      $.ajax({
        type: 'GET',
        url: `${apiUrl}/s/products/${productId}`,
        contentType: 'application/json',
        success: res => {
          console.log(res)
          if (res.totalLimit === 0 || res.totalSoldCount <= res.totalLimit) {
            submitOrder()
          } else {
            utils.toast('本次名额已抢完')
          }
        },
        error: err => {
          const error = JSON.parse(err.response)
          console.error(error.message)
        }
      })
    }
  })

  // 切换账号
  $('.switch-account').off('click').on('click', e => {
    account.ajax({
      type: 'DELETE',
      path: '/s/user/social/wx-jqfx',
      async: false
    })
    $('.login').show()
    $('.user-info').hide()
  })

  //启动计时器
  function setTime () {
    if (countdown > 0) {
      $('#getCode').attr('disabled', true)
      $('#getCode').text('重新发送(' + countdown + 's)')
    } else {
      $('#getCode').attr('disabled', null)
      $('#getCode').text('发送验证码')
      countdown = 60
      return
    }
    countdown--

    setTimeout(arguments.callee, 1000)
  }

  // 发送验证码
  function sendCode (mobile) {
    $.ajax({
      type: 'POST',
      url: `${apiUrl}/s/user/sms/login`,
      data: JSON.stringify({mobile}),
      contentType: 'application/json',
      success: () => {
        setTime()
        utils.toast('验证码已经发送')
      },
      error: err => {
        const error = JSON.parse(err.response)
        console.error(error.message)
      }
    })
  }

  // 手机号登录
  function login (mobile, smsCode, callback) {
    $.ajax({
      type: 'POST',
      url: `${apiUrl}/s/user/login/sms`,
      data: JSON.stringify({
        mobile,
        smsCode,
        channel
      }),
      contentType: 'application/json',
      success: data => {
        countdown = 0
        window.userInfo = data
        window.access_token = data.access_token
        account._saveToken(data)
        if (utils.isWeChat()) {
          $.ajax({
            type: 'POST',
            url: `${apiUrl}/s/user/social`,
            headers: {'Authorization': `Bearer ${data.access_token}`},
            data: JSON.stringify({
              socialType: 'wx-jqfx',
              socialCode: utils.getQueryString('code')
            }),
            contentType: 'application/json',
            success: result => {
              account.socialBinded = true
              account._saveOpenId(result.socialId)
              window.openId = result.socialId
              callback()
            }
          })
        } else {
          callback()
        }
      },
      error: err => {
        const error = JSON.parse(err.response)
        console.error(error.message)
      }
    })
  }

  // 购买下单
  function submitOrder () {
    const accessString = window.localStorage.getItem('QKidsAccess')
    const access = JSON.parse(accessString)
    window.access_token = access.access_token
    const openId = window.localStorage.getItem('QKidsOpenId')
    window.openId = openId
    $.ajax({
      type: 'POST',
      url: `${apiUrl}/s/bills`,
      headers: {'Authorization': `Bearer ${access_token}`},
      data: JSON.stringify({
        productId,
        openId,
        payChannel: utils.isWeChat() ? 'weixin' : 'alipay',
        returnUrl: verifyUrl,
        tradeType: 'JSAPI',
        referenceCode: utils.getUrlParam('rid') ? `OneOnOne-${utils.getUrlParam('rid')}` : ''
      }),
      contentType: 'application/json',
      success: data => {
        window.location.href = verifyUrl
      },
      error: e => {
        const err = JSON.parse(e.response)
        if (err.code === 'product.rejected.by.bought.products') utils.toast('已领取过体验课时')
        else utils.error(err)
      }
    })
  }
})

function init () {
  setShare()
  window.productId = getProductId()
  window.channel = getChannel()
  utils.initAnalytics('order')
  analytics.send({
    event: `${av}-open`,
    attr: {
      pid: productId || '',
      _c: channel || ''
    }
  })
  window.apiUrl = 'https://gate.97kid.com'
  window.verifyUrl = `${window.location.protocol}//${window.location.host}/wx/verify${Math.ceil(Math.random() * 100)}?pid=${productId}&_c=${channel}`
  window.account = new Account()
  account.forceLogin = false
  account.getUserInfo((err, userInfo) => {
    if (!err) {
      console.log('已经登录')
      console.log(userInfo)
      if (userInfo.headerSmall) $('.user-info .avatar').attr('src', userInfo.headerSmall)
      $('.user-info .nickname').text(userInfo.nickname)
      $('.login').hide()
      $('.user-info').show()
    } else {
      console.log('没有登录')
      $('.login').show()
      $('.user-info').hide()
    }
  })
}

function setShare () {
  window.wxconfig = new WxConfig(wechatConfig, '')
  window.shareFlag = ''
  const userInfo = JSON.parse(window.localStorage.getItem('QKidsUserInfo'))
  if (userInfo && userInfo.shareFlag) window.shareFlag = userInfo.shareFlag
  if (utils.isWeChat()) wxconfig.activeShare(shareFlag, '', {
    title: '【Qkids久趣】4-12岁，在家跟北美外教学英语，新用户100元体验！',
    desc: '严选北美外教在线授课，创造趣味十足的课堂体验，让孩子爱学更有效。',
    link: `${window.location.protocol}//${window.location.host}/wx${Math.ceil(Math.random() * 100)}?_r=${shareFlag}`,
    imgUrl: 'https://static-app.97kid.com/site-student/public/img/share.png'
  })
}

function getProductId () {
  if (utils.getQueryString('pid')) return utils.getQueryString('pid')
  else {
    if (utils.getQueryString('state')) {
      if (utils.getQueryString('state').length > 0) return utils.getQueryString('state').split('+++')[0]
      else return ''
    }
  }
}

function getChannel () {
  if (utils.getQueryString('_c')) return utils.getQueryString('_c')
  else {
    if (utils.getQueryString('state')) {
      if (utils.getQueryString('state').length > 1) return utils.getQueryString('state').split('+++')[1]
      else return ''
    }
  }
}